import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import * as bcrypt from 'bcryptjs';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async create(createUserDto: CreateUserDto): Promise<User> {
    const { username, email, phone, password } = createUserDto;
    // 检查唯一性
    const exist = await this.userRepository.findOne({
      where: [
        { username },
        { email },
        ...(phone ? [{ phone }] : []),
      ],
    });
    if (exist) {
      throw new BadRequestException('用户名、邮箱或手机号已存在');
    }
    // 密码加密
    const hash = await bcrypt.hash(password, 10);
    const user = this.userRepository.create({ ...createUserDto, password: hash });
    return this.userRepository.save(user);
  }

  async findByUsernameOrEmail(usernameOrEmail: string): Promise<User | undefined> {
    const user = await this.userRepository.findOne({
      where: [
        { username: usernameOrEmail },
        { email: usernameOrEmail },
      ],
    });
    return user || undefined;
  }

  async findById(id: number): Promise<User | undefined> {
    const user = await this.userRepository.findOne({ where: { id } });
    return user || undefined;
  }

  async findAll(): Promise<User[]> {
    return this.userRepository.find();
  }

  async remove(id: number): Promise<void> {
    await this.userRepository.delete(id);
  }
}
